package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import model.domain.UserInfo;
import model.mongo.Movement;
import model.vo.MovementsVo;
import model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ManagerService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    public PageResult findAllUsers(Integer page, Integer pagesize) {
        //1、调用API分页查询数据列表   Ipage<UserInfo>
        IPage<UserInfo> iPage = userInfoApi.findAll(page, pagesize);
        //2、需要将Ipage转化为PageResult
        PageResult result = new PageResult(page, pagesize, iPage.getTotal(), iPage.getRecords());
        //3、构造返回值
        return result;
    }

    public UserInfo findUserById(Long userId) {
        return userInfoApi.findById(userId);
    }

    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        return videoApi.findByUserId(page, pagesize, uid);
    }

    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        PageResult result = movementApi.findByUserId(uid, state, page, pagesize);

        List<Movement> items = (List<Movement>) result.getItems();
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }

        List<Long> userId = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userId, null);

        ArrayList<MovementsVo> movementsVos = new ArrayList<>();

        for (Movement item : items) {
            UserInfo userInfo = map.get(item.getUserId());
            if (userInfo != null) {
                MovementsVo movementsVo = MovementsVo.init(userInfo, item);
                movementsVos.add(movementsVo);
            }
        }
        result.setItems(movementsVos);
        return result;
    }
}
